﻿using LanDBom.Models;
using LanDBom.Models.Algorithm;
using LanDBom.Models.Procure;
using Microsoft.Ajax.Utilities;
using Microsoft.Office.Interop.Excel;
using Newtonsoft.Json;
using NPOI.POIFS.FileSystem;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using System;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Services.Description;
using static System.Net.Mime.MediaTypeNames;
using System.Web.UI.HtmlControls;
using System.Data;
using LanDBom.Models.Admin;
using iTextSharp.text;
using LanDBom.Models.price_New_2;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using Newtonsoft.Json.Linq;
using Humanizer.Localisation;
using OfficeOpenXml.DataValidation;
using OfficeOpenXml;
using static System.Windows.Forms.AxHost;
using NPOI.HSSF.UserModel;
using NPOI.SS.Util;
using System.Windows.Media;
using System.Drawing;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using static NPOI.HSSF.Record.UnicodeString;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using OfficeOpenXml.FormulaParsing.Excel.Operators;
using PuppeteerSharp.Media;
using System.Data.Entity.Validation;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using System.Windows.Documents;
using System.EnterpriseServices;
using System.Security.Cryptography;
using System.Web.UI.WebControls.WebParts;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using FastReport.Barcode;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Status;
using System.Windows;

namespace LanDBom.Controllers
{
    public class MaterialController : Controller
    {
        Find_APP_information find_APP = new Find_APP_information();
        LDbaseEntities db = new LDbaseEntities();
        Find_BOMini mini = new Find_BOMini();
        Find_Libary Find_Libary = new Find_Libary();
        GY_Algorithm GY = new GY_Algorithm();
        Admin__Append ad = new Admin__Append();
        JChelp chelp = new JChelp();
        Find_P FP = new Find_P();
        Bought bu = new Bought();
        // GET: Material
        public ActionResult Index(string names, string aewd, string bid, string fro, string BOM2_wuLiu = "", string BOM2_liao = "", string Zongjsia = "", string BOM2_id = "", string Ap_bian = "", int state = 0, int num = 0)
        {
            //names = "SQ202311219556113 ";
            names = names == null ? "-1" : names;
            List<Applications> xian = db.Applications.Where(a => a.AP_bian == names).ToList();/*查询客户*/
            /*遍历工艺库是工艺根据种类分类*/
            var Yinshua = db.libray.ToList();  //印刷--1，结合--21，模具--22，表面处理--2，吸塑--6
            ViewBag.Yinshua = Yinshua;  //传递到前台--印刷
            var ListZBxx = FP.find_lib();
            ViewBag.ListZBxx = ListZBxx;
            ViewBag.ListPP = FP.find_manufacturer();
            ViewBag.ListZL = FP.find_ZL_();
            ViewBag.ListPO = FP.find_projectprs();
            ViewBag.parice = FP.find_parices();
            ViewBag.ro = FP.find_Rou();
            ViewBag.par = FP.find_parices();
            ViewBag.par_hc = FP.find_Rou_HC();
            ViewBag.Yun = FP.YUNF();
            ViewBag.JX = FP.jicsin();
            ViewBag.ro_xs = FP.find_Rou_XS();
            var dhf = mini.B_findnext(BOM2_wuLiu, BOM2_liao, names);
            dhf = dhf.OrderBy(s => s.BOM2_BQing).ToList();
            foreach (var d in xian)
            {
                dhf = dhf.Where(p => p.BOM2_Zhuang == d.App_BanB).ToList();
            }
            ViewBag.F_kehu = xian;
            ViewBag.F_bom = dhf;
            if (state == 0)
            {
                Session["appp_id"] = aewd;
                Session["for"] = fro;
                Session["bid"] = bid;
            }

            //查找物料信息(模糊查询)
            if (state == 1)
            {
                var listBOMw = dhf;
                List<BOMini> list2 = new List<BOMini>();
                foreach (BOMini b in listBOMw)
                {
                    var jeiji = b.BOM2_BQing + "-";
                    int twwe = listBOMw.Where(x => x.BOM2_BQing.Contains(jeiji)).Count();
                    if (twwe == 0)
                    {
                        list2.Add(b);
                    }
                }
                var list = from a in list2 select new { a.BOM2_id, a.BOM2_chen, a.BOM2_duan, a.BOM2_liao, a.BOM2_wuLiu, a.BOM2_Nian, a.BOM2_Yong, a.BOM2_Sone, a.BOM2_BQing, a.BOM2_Guige, a.BOM2_ST, a.BOM2_Lei, BOM2_mioa = a.operational == null ? "0" : a.operational.OP_price.ToString() };
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    Formatting = Formatting.Indented
                };
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 2)
            {
                var temp = db.Formation.Where(x => x.FM_bai == BOM2_liao).ToList();
                var list = from a in temp
                           select new { a.FM_name, a.FM_bai, a.FM_nyl, a.FM_zx, a.FM_bmcl, a.FM_ycl, a.FM_yj, a.FM_ej, a.FM_long, a.FM_kuan, a.FM_gao, a.FM_ms, a.FM_ji, a.FM_Jieti, a.FM_Zhuang };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 3)
            {
                var temp = db.duty.Where(x => x.dl_id == num).ToList();
                var list = from a in temp
                           select new { a.du_id, a.du_name };

                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }

            else if (state == 4)
            {
                var shunf = chelp.Shungdint(BOM2_id);
                return Content(shunf.ToString(), "application/json");
            }
            else if (state == 5)
            {
                string ren = db.Applications.Where(x => x.AP_bian == Ap_bian).FirstOrDefault().AP_ren;
                return Content(ren);
            }
            else if (state == 7)//保存价格
            {
                var obmijd = int.Parse(BOM2_id);
                var shfnji = db.BOMini.FirstOrDefault(s => s.BOM2_id == obmijd);
                //保存到工艺库
                var shufn = new operational()
                {
                    OP_price = (decimal?)double.Parse(Zongjsia),
                };
                db.operational.Add(shufn);
                int shun = db.SaveChanges();
                string messsaege = "";
                if (shun == 1)
                {
                    shfnji.BOM2_Gong = shufn.OP_ID;
                    db.Entry(shfnji).State = EntityState.Modified;
                    int sun = db.SaveChanges();
                    messsaege = sun > 0 ? "添加成功" : "添加失败";
                }
                else
                {
                    messsaege = "保存失败，请重试";
                }
                return Content(messsaege);
            }
            else if (state == 8)
            {
                //遍历BOM并删除成本记录
                var app = db.Applications.FirstOrDefault(k => k.AP_bian == Ap_bian);
                var ban = app.App_BanB;
                var bomin = db.BOMini.Where(a => a.BOM2_bian == Ap_bian && a.BOM2_Zhuang == ban).ToList();
                foreach (var item in bomin)
                {
                    var bina = item.BOM2_Gong;
                    var shu = db.operational.FirstOrDefault(v => v.OP_ID == bina);
                    if (shu == null)
                    {
                        continue;
                    }
                    db.operational.Remove(shu);
                }
                int s = db.SaveChanges();
                return Content(s.ToString());
            }
            else if (state == 9)
            {
                var baot = db.ProcessRecord.Where(x => x.wl_liao == BOM2_liao).FirstOrDefault();
                db.Configuration.LazyLoadingEnabled = false;

                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(baot, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 10)
            {
                var list = db.CraftMaterials.Where(x => x.prr_id == num).ToList();
                var temp = from a in list
                           select new { a.prrw_zc, a.prrw_c, a.prrw_k, a.prrw_g, a.prrw_jia, a.prrw_shu, a.prrw_sh, a.prrw_guige };

                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 11)
            {
                string zhuang = "";
                var bom = db.BOMini.Where(x => x.BOM2_id == num).FirstOrDefault();
                string name = bom.BOM2_sdname;
                var tihuans = db.Dengli.Where(x => x.DE_nae == name).FirstOrDefault();
                var inde = tihuans == null ? "" : tihuans.DE_dksj;
                if (bom != null)
                {
                    if (bom.BOM2_sd == "锁定" && inde == "1")
                    {
                        if (bom.BOM2_sdname == Zongjsia)
                        {
                            zhuang = "通过";
                        }
                        else
                        {

                            zhuang = bom.BOM2_sdname + "正在进行工艺配置，请选择其他物料";
                        }
                    }
                    else
                    {
                        zhuang = "通过";
                        bom.BOM2_sd = "锁定";
                        bom.BOM2_sdname = Zongjsia;
                        db.SaveChanges();
                    }
                }
                return Content(zhuang);
            }
            else if (state == 12)
            {
                var bom = db.BOMini.Where(x => x.BOM2_id == num).FirstOrDefault();
                if (bom != null)
                {
                    bom.BOM2_sd = null;
                    bom.BOM2_sdname = null;
                    db.SaveChanges();
                }
            }
            else if (state == 13)
            {
                var list = db.ProcessFlow.Where(x => x.prr_id == num).ToList();
                var temp = from a in list
                           select new { a.pfw_zc, a.pfw_jia, a.CL_beizhu };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 14)
            {
                var BAN = db.Applications.Where(s => s.AP_bian == Ap_bian).FirstOrDefault().App_BanB;
                var AllBom = db.BOMini.Where(x => x.BOM2_bian == Ap_bian && x.BOM2_Zhuang == BAN && x.BOM2_chen == "Leve0").ToList();//全部BOM
                int shu = 0;
                foreach (BOMini b in AllBom)
                {
                    BOMini temp = db.BOMini.Where(x => x.BOM2_id == b.BOM2_id).FirstOrDefault();
                    temp.BOM2_GY = "完成";
                    db.Entry(temp).State = EntityState.Modified;
                    shu += db.SaveChanges();
                }
                string meagr = shu == AllBom.Count() ? "1" : "0";
                return Content(meagr);
            }

            return View();
        }
        public ActionResult cghangessw(string hu)
        {
            var qasd = db.BOMini.Where(x => x.BOM2_bian == hu).ToList();
            if (qasd.Count > 0)
            {
                foreach (BOMini wd in qasd)
                {
                    wd.BOM2_GY = "完成";
                    db.SaveChanges();
                }
            }
            var bominiji = db.BOMini.Where(s => s.BOM2_bian == hu).ToList();
            var sjshd = GY.Tprice(bominiji);
            return Json(hu);
        }
        public ActionResult djkebd(string bu)
        {
            int shu = 0;
            string mess = "";
            using (LDbaseEntities fanh = new LDbaseEntities())
            {
                var qasd2 = fanh.BOMini.Where(x => x.BOM2_bian == bu).ToList();
                if (qasd2.Count > 0)
                {
                    foreach (BOMini wd in qasd2)
                    {
                        string lh = wd.BOM2_liao;
                        Formation formation = fanh.Formation.Where(x => x.FM_bai == lh).FirstOrDefault();
                        formation.FM_price = (decimal?)double.Parse(wd.BOM2_CB);
                        fanh.Entry(formation).State = EntityState.Modified;
                        shu += fanh.SaveChanges();
                    }
                }
                mess = shu == qasd2.Count ? "提交成功" : "提交失败";
            }
            return Json(mess);
        }

        public ActionResult cghange(List<BOMini> b2)
        {
            string appbian = "";
            //修改BOMINi数据状态
            foreach (BOMini b in b2)
            {
                BOMini temp = db.BOMini.Where(x => x.BOM2_id == b.BOM2_id).FirstOrDefault();
                temp.BOM2_GY = "完成";
                db.SaveChanges();
                appbian = temp.BOM2_bian;
            }
            var BAN = db.Applications.Where(s => s.AP_bian == appbian).FirstOrDefault().App_BanB;
            var bominiji = db.BOMini.Where(s => s.BOM2_bian == appbian && s.BOM2_Zhuang == BAN).ToList();
            var sjshd = GY.Tprice(bominiji);
            string zhuang = "";
            int index = 0;//记录工艺是否做完
            int index2 = 0;//记录是否自制
            int index3 = 0;//记录外购件工艺是否完成
            int index4 = 0;//记录自制件工艺是否完成
            //判断有多层是将leve0 成也改成完成
            var sdw = new List<BOMini>();
            var listBOMw = db.BOMini.Where(x => x.BOM2_bian == appbian && x.operational.OP_ID == x.BOM2_Gong && x.BOM2_Zhuang == BAN).ToList();
            foreach (BOMini b in listBOMw)
            {
                var jeiji = b.BOM2_BQing;
                int twwe = listBOMw.Where(x => x.BOM2_BQing != jeiji && x.BOM2_BQing.Contains(jeiji)).Count();
                if (twwe == 0)
                {
                    sdw.Add(b);
                }
            }
            var list = db.BOMini.Where(x => x.BOM2_bian == appbian && x.BOM2_Zhuang == BAN).ToList();//全部BOM
            Applications app = db.Applications.Where(x => x.AP_bian == appbian).FirstOrDefault();//单据
            foreach (BOMini bom in sdw)
            {
                if (bom.BOM2_GY != "完成")
                {
                    index++;
                }
                if (bom.BOM2_Lei == "外购")
                {
                    index2++;
                }
                if (bom.BOM2_GY != "完成" && bom.BOM2_Lei == "外购")
                {
                    index3++;
                }
                if (bom.BOM2_GY != "完成" && bom.BOM2_Lei == "自制")
                {
                    index4++;
                }
            }

            if (index2 == 0)
            {
                //自制
                app.App_bu = "6";
                db.SaveChanges();
                //补全数据结构  ---CB：结构：供应商：阶梯：价格，
                LDbaseEntities LD = new LDbaseEntities();
                var BOMI = db.BOMini.Where(s => s.BOM2_bian == appbian).ToList();
                foreach (var item in BOMI)
                {
                    var HJ = LD.Formation.Where(s => s.FM_bai == item.BOM2_liao).FirstOrDefault();
                    var huj = "";

                    if (item.BOM2_CB == null)
                    {
                        var HHN = HJ.FM_Jieti.Split(',');
                        huj = item.BOM2_CB;
                        if (HHN.Length > 1)
                        {
                            foreach (var A in HHN)
                            {
                                huj += ":" + A + ":" + item.BOM2_CB;
                            }
                        }
                        else
                        {
                            huj = ":1:" + item.BOM2_CB;
                        }
                    }
                    else
                    {
                        var LP = item.BOM2_CB.Split(':');
                        if (LP.Length <= 1)
                        {
                            if (HJ != null)
                            {
                                var HHN = HJ.FM_Jieti.Split(',');
                                if (item.BOM2_Gong == null && item.BOM2_Gong.ToString() == "")
                                {
                                    huj = "0:1:" + item.BOM2_CB + ",";
                                }
                                else
                                {
                                    var GON = int.Parse(item.BOM2_Gong.ToString());
                                    var shun = LD.operational.Where(s => s.OP_ID == GON).FirstOrDefault();
                                    var sh = shun == null ? 0.0 : (double)shun.OP_price;
                                    for (int i = 0; i < HHN.Length; i++)
                                    {
                                        var JJI = "0:" + HHN[i] + ":" + sh;
                                        huj += JJI + ",";
                                    }
                                }
                            }
                        }
                        else
                        {
                            huj = item.BOM2_CB;
                        }
                    }
                    item.BOM2_CB = huj;
                    db.Entry(item).State = EntityState.Modified;
                    db.SaveChanges();
                }
                zhuang = "已完成工艺配置，请前往对外报价";
            }
            else
            {//混合
                if (index3 != 0)
                {
                    zhuang = "等待其他物料进行工艺配置";
                }
                else
                {
                    var WG = list.Where(s => s.BOM2_Lei == "外购").ToList().Count();
                    var XUNjia = list.Where(s => (s.BOM2_sunhao == "已询价" || s.BOM2_sunhao == "已核价") && s.BOM2_GY == "完成" && s.BOM2_Lei == "外购").ToList().Count();
                    if (WG == XUNjia)
                    {
                        app.App_bu = "5";
                        db.SaveChanges();
                        zhuang = "外购件已完成工艺配置和询价，请前往物料核价！";
                    }
                    else
                    {
                        if (app.App_bu == "3")
                        {
                            app.App_bu = "4";
                            db.SaveChanges();
                            zhuang = "已完成工艺配置，请前往物料询价";
                        }
                        else
                        {
                            app.App_bu = "5";
                            db.SaveChanges();
                            zhuang = "已完成工艺配置和物料询价，请前往物料核价价";
                        }
                    }
                }
                //走询价流程中自制物料的情况
                if (index4 != 0)
                {
                    zhuang = "外购物料已全部进行工艺配置，等待自制物料进行工艺配置！采购继续下面流程！";
                }
                else
                {
                    var ZZZ = list.Where(s => s.BOM2_Lei == "自制").ToList().Count();
                    var XUNjia = list.Where(s => s.BOM2_GY == "完成" && s.BOM2_Lei == "自制").ToList().Count();
                    if (ZZZ == XUNjia)
                    {
                        if (app.App_bu == "5")
                        {
                            string SHiji = bu.Levesjin(app.AP_bian);
                            app.App_bu = "6";
                            db.Entry(app).State = EntityState.Modified;
                            var temp = db.SaveChanges();
                            zhuang = temp > 0 ? "采购处理结束 请前往对外报价" : "错误未通过";
                        }
                        else
                        {
                            zhuang = "等待采购处理";
                        }
                    }
                }
            }
            return Json(zhuang);
        }
        public ActionResult changeBOMzhuanb(List<BOMini> bs)
        {
            foreach (BOMini bom in bs)
            {
                string messsaege = "";
                BOMini temp = db.BOMini.Where(x => x.BOM2_id == bom.BOM2_id).FirstOrDefault();
                temp.BOM2_sunhao = bom.BOM2_sunhao;
                db.SaveChanges();
                int num = db.BOMini.Where(x => x.BOM2_bian == bom.BOM2_bian).Count();
                int index = db.BOMini.Where(x => x.BOM2_bian == bom.BOM2_bian && x.BOM2_sunhao == "完成").Count();
                if (num == index)
                {
                    Applications applications = db.Applications.Where(x => x.AP_bian == bom.BOM2_bian).FirstOrDefault();
                    if (applications.App_bu == "3")
                    {
                        if (applications.App_lei == "自制")
                        {
                            applications.App_bu = "6";
                            messsaege = "自制件工艺完成";
                        }
                        else
                        {
                            applications.App_bu = "4";
                            messsaege = "工艺完成";
                        }
                    }
                    else if (applications.App_bu == "4")
                    {
                        applications.App_bu = "5";
                        messsaege = "工艺配置，物料询价已完成";
                    }
                    int rows = db.SaveChanges();


                }
                return Json(messsaege);
            }

            return View();
        }


        //添加工艺库添加
        public ActionResult AddGong(libray da, string LB_bai = "", string FenL = "", string FenBian = "", string LB_fne = "", string ST_fne = "", int stantes = 0)
        {
            List<libray> librays = db.libray.ToList();
            List<Steelmaking> steelmakings = db.Steelmaking.ToList();
            List<libray> shun = Find_Libary.Edites(LB_bai, LB_fne, ST_fne);
            ViewBag.S_tea = steelmakings;
            if (stantes == 1)
            {
                var operats = from s in librays
                              join a in steelmakings on s.ST_ID equals a.ST_ID
                              select new { s.LB_ID, s.LB_bai, s.LB_fne, s.ST_ID, a.ST_fne, s.LB_dan, s.LB_jia, s.LB_shun };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operats, settings);

                return Content(jsongStr, "application/json");
            }
            if (stantes == 2)
            {
                var operat = from s in shun
                             join a in steelmakings on s.ST_ID equals a.ST_ID
                             select new { s.LB_ID, s.LB_bai, s.LB_fne, s.ST_ID, a.ST_fne, s.LB_dan, s.LB_jia, s.LB_shun };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operat, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 3)
            {
                db.libray.Add(da);
                int m = db.SaveChanges();
                string message = m > 0 ? "保存成功" : "保存失败";
                var operats = from s in librays
                              join a in steelmakings on s.ST_ID equals a.ST_ID
                              select new { s.LB_ID, s.LB_bai, s.LB_fne, s.ST_ID, a.ST_fne, s.LB_dan, s.LB_jia, s.LB_shun };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operats, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 4)
            {
                Steelmaking ste = new Steelmaking()
                {
                    ST_bai = FenBian,
                    ST_fne = FenL,
                };
                db.Steelmaking.Add(ste);
                int shukn = db.SaveChanges();
                var jsongStrsss = shukn > 0 ? "添加成功" : "添加失败";
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(jsongStrsss, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 9)
            {
                var Stement = db.Steelmaking.OrderByDescending(s => s.ST_ID).FirstOrDefault();
                var jhjj = Stement.ST_bai.ToString();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(jhjj, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
        //供应商
        public ActionResult AddGS(List<Providers> das, Providers da, flow flow, string shen = "", string ming = "", string namws = "", string shi = "", string shund = "", int stantes = 0, int id = 0)
        {
            List<Providers> shun = Find_Libary.EditeGS(shen, ming, shi);
            List<Providers> pro = shun.Where(x => x.PR_bei == "准入" || x.PR_bei == "临时").ToList();
            List<Providers> pro2 = db.Providers.Where(x => x.PR_bei == "保存").ToList();
            List<Providers> pro3 = db.Providers.Where(x => x.PR_bei == "临时").ToList();

            ViewBag.count2 = pro3.Count;
            ViewBag.count = pro2.Count;
            ViewBag.Liao = db.buty2.ToList();
            ViewBag.temp21 = db.buty3.ToList();
            var Jins = shund == "" ? 0 : int.Parse(shund);
            var tes = pro.Count();//行数
            var yeshu = Math.Ceiling((double)tes / 10);//页数
            ViewBag.Yeshu = tes;
            ViewBag.Shund = yeshu;
            pro = pro.Skip(Jins * 10).Take(10).ToList();

            if (stantes == 1)
            {
                var operats = from s in pro
                              select new { s.PR_ID, s.PR_bian, s.PR_name, s.PR_di, s.PR_lian, s.PR_you, s.PR_bei, s.PR_Lei1, s.PR_Lei2 };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operats, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 2)
            {
                var operat = from s in shun
                             select new { s.PR_ID, s.PR_bian, s.PR_name, s.PR_di, s.PR_lian, s.PR_you, s.PR_bei };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operat, settings);

                return Content(jsongStr, "application/json");
            }
            if (stantes == 3)
            {
                var list = db.Providers.Where(x => x.PR_bian == namws).ToList();
                var operat = from s in list
                             select new { s.PR_ID, s.PR_name, s.PR_bian, s.PR_you, s.PR_di, s.PR_lian, s.PR_bei, s.PR_hang, s.PR_nsrjdh, s.PR_yhzh, s.PR_gswz, s.PR_dzfs, s.PR_fktj, s.PR_dhdz, s.PR_cgy, s.PR_qyxz, s.PR_khyh, s.PR_fr, s.PR_lxr, s.PR_jsfs, s.PR_jsbz, s.PR_dhfs, s.PR_qd, s.PR_zl, s.PR_LIDH, s.PR_lyqd, s.PR_jer, s.PR_Lei1, s.PR_Lei2 };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operat, settings);
                return Content(jsongStr, "application/json");

            }
            if (stantes == 4)
            {
                string temp = db.Providers.Where(x => x.PR_bian == namws).First().PR_ID.ToString();
                return Content(temp, "application/json");
            }
            if (stantes == 5)
            {
                string temp = db.Providers.Where(x => x.PR_bian == namws).Count().ToString();
                return Content(temp, "application/json");
            }
            if (stantes == 6)
            {
                var ppools = db.Providers.FirstOrDefault(s => s.PR_ID == da.PR_ID);
                ppools.PR_name = da.PR_name;
                ppools.PR_you = da.PR_you;
                ppools.PR_lian = da.PR_lian;
                ppools.PR_di = da.PR_di;
                ppools.PR_bei = da.PR_bei;
                db.Entry(ppools).State = EntityState.Modified;
                int wenm = db.SaveChanges();
                string powasd = wenm > 0 ? "修改成功" : "修改失败";
                return Content(powasd);
            }
            if (stantes == 7)
            {
                var wxxss = int.Parse(namws);
                var plpkok = db.Providers.FirstOrDefault(s => s.PR_ID == wxxss);
                var For = db.Formation.Where(s => s.PR_ID == wxxss).ToList();
                foreach (var jin in For)
                {
                    jin.PR_ID = null;
                    db.Entry(jin).State = EntityState.Modified;
                }
                var sys = db.system.Where(x => x.pro_id == wxxss).FirstOrDefault();
                if (sys != null)
                {
                    db.system.Remove(sys);
                }
                var li = db.flow.Where(x => x.pr_id == wxxss).FirstOrDefault();
                if (li != null)
                {
                    db.system.Remove(sys);
                }
                //删除或禁用对饮审批流
                string FCode = plpkok.PR_bian;
                List<shenpingliu> list1 = db.shenpingliu.Where(x => x.FJINF == FCode).ToList();
                foreach (var item in list1)
                {
                    item.Fzhuang = "结束";
                    db.Entry(item).State = EntityState.Modified;
                    int shulll = db.SaveChanges();
                }
                int sji = db.SaveChanges();
                int sungko = 0;
                db.Providers.Remove(plpkok);
                sungko = db.SaveChanges();
                string messs = sungko > 0 ? "删除成功" : "删除失败";
                return Content(messs);
            }
            if (stantes == 8)
            {
                var list = db.flow.Where(x => x.pr_id == id).ToList();
                var temp = from s in list
                           select new { s.fl_cfmj, s.fl_ys, s.fl_turnover1, s.fl_turnover2, s.fl_turnover3, s.fl_gslb, s.fl_gykh, s.fl_zrs, s.fl_sqyy, s.fl_clsj, s.fl_cgsp };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 9)
            {

                var listcer = db.certificate.Where(x => x.por_id == id).ToList();
                var listtil = db.toc.ToList();

                var operats = from a in listtil
                              join b in listcer on a.toc_id equals b.toc_id into c
                              from d in c.DefaultIfEmpty()
                              select new { a.toc_id, a.toc_name, cer_name = d == null ? "" : d.cer_name, cer_wen = d == null ? "" : d.cer_wen };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operats, settings);
                return Content(jsongStr, "application/json");

            }
            if (stantes == 10)
            {
                var listcer = db.profile.Where(x => x.por_id == id).ToList();
                var listtil = db.dt.ToList();

                var operats = from a in listtil
                              join b in listcer on a.dt_id equals b.dt_id into c
                              from d in c.DefaultIfEmpty()
                              select new { a.dt_id, a.dt_name, pf_name = d == null ? "" : d.pf_name, pf_wen = d == null ? "" : d.pf_wen };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operats, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 11)
            {
                var list = db.system.Where(x => x.pro_id == id).ToList();
                var temp = from a in list
                           select new { a.sys_fl, a.sys_fw, a.sys_tgbg, a.sys_tgrz, a.sys_jltx, a.sys_wbxk, a.sys_jckq, a.sys_pjjg, a.sys_sx, a.sys_syzl };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 12)
            {
                var operats = from s in pro2
                              select new { s.PR_ID, s.PR_bian, s.PR_name, s.PR_di, s.PR_lian, s.PR_you, s.PR_bei };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operats, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 13)
            {
                string pro2_s = db.Providers.Count().ToString();
                return Content(pro2_s, "application/json");
            }
            if (stantes == 14)
            {
                var list = db.Jixing.Where(x => x.gys_id == id).ToList();
                var operats = from s in list
                              select new { s.sb_id, s.sb_name, s.sb_pingpai, s.sb_gongxu, s.sb_zuida, s.sb_zuixiao, s.sb_channeng, s.sb_renli, s.sb_zuiho, s.sb_zuibiao, s.sb_kaicao_x, s.sb_kaicao_d, s.sb_yingshua_d, };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operats, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 15)
            {
                Jixing jixing = db.Jixing.Where(x => x.sb_id == id).FirstOrDefault();
                db.Jixing.Remove(jixing);
                int temp = db.SaveChanges();
                string powasd = temp > 0 ? "删除成功" : "删除失败";
                return Content(powasd, "application/json");

            }
            if (stantes == 16)
            {
                var operats = from s in pro3
                              select new { s.PR_ID, s.PR_bian, s.PR_name, s.PR_di, s.PR_lian, s.PR_you, s.PR_bei };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(operats, settings);
                return Content(jsongStr, "application/json");
            }
            if (stantes == 17)
            {
                var Jieg = db.Providers.Where(s => s.PR_bian == namws).FirstOrDefault();
                var shu = Jieg == null ? "N" : "Y";
                return Content(shu);
            }
            return View(pro);
        }
        public ActionResult addjinx(List<Jixing> jixings)
        {
            foreach (Jixing d in jixings)
            {
                db.Jixing.Add(d);
                int temp = db.SaveChanges();
                string powasd = temp > 0 ? "添加成功" : "添加失败";
                return Json(powasd);
            }
            return View();
        }

        public ActionResult addgongys(List<Providers> das)
        {
            foreach (Providers d in das)
            {
                int temp = db.Providers.Where(x => x.PR_bian == d.PR_bian).Count();
                if (temp > 0)
                {
                    Providers providers = db.Providers.Where(s => s.PR_bian == d.PR_bian).First();
                    providers.PR_bei = d.PR_bei;
                    providers.PR_cgy = d.PR_cgy;
                    providers.PR_dhdz = d.PR_dhdz;
                    providers.PR_dhfs = d.PR_dhdz;
                    providers.PR_zl = d.PR_zl;
                    providers.PR_you = d.PR_you;
                    providers.PR_yhzh = d.PR_yhzh;
                    providers.PR_qyxz = d.PR_qyxz;
                    providers.PR_di = d.PR_di;
                    providers.PR_dzfs = d.PR_dzfs;
                    providers.PR_fktj = d.PR_fktj;
                    providers.PR_fr = d.PR_fr;
                    providers.PR_gswz = d.PR_gswz;
                    providers.PR_jsbz = d.PR_jsbz;
                    providers.PR_jsfs = d.PR_jsfs;
                    providers.PR_khyh = d.PR_khyh;
                    providers.PR_Lei1 = d.PR_Lei1;
                    providers.PR_Lei2 = d.PR_Lei2;
                    providers.PR_lian = d.PR_lian;
                    providers.PR_lxr = d.PR_lxr;
                    providers.PR_lxrsj = d.PR_lxrsj;
                    providers.PR_name = d.PR_name;
                    providers.PR_nsrjdh = d.PR_nsrjdh;
                    providers.PR_qd = d.PR_qd;
                    providers.PR_hang = d.PR_hang;
                    providers.PR_lyqd = d.PR_lyqd;
                    providers.PR_jer = d.PR_jer;
                    providers.PR_LIDH = d.PR_LIDH;
                    db.SaveChanges();
                    return Json("添加成功");
                }
                else
                {
                    db.Providers.Add(d);
                    int index = db.SaveChanges();
                    string powasd = index > 0 ? "添加成功" : "添加失败";
                    return Json(powasd);
                }
            }
            return View();
        }
        public ActionResult addliuc(List<flow> flows)
        {
            foreach (flow flow in flows)
            {
                int index = db.flow.Where(x => x.pr_id == flow.pr_id).Count();
                if (index > 0)
                {
                    flow temp = db.flow.Where(s => s.pr_id == flow.pr_id).FirstOrDefault();
                    temp.fl_cfmj = flow.fl_cfmj;
                    temp.fl_cgsp = flow.fl_cgsp;
                    temp.fl_clsj = flow.fl_clsj;
                    temp.fl_gslb = flow.fl_gslb;
                    temp.fl_gykh = flow.fl_gykh;
                    temp.fl_sqyy = flow.fl_sqyy;
                    temp.fl_turnover1 = flow.fl_turnover1;
                    temp.fl_turnover2 = flow.fl_turnover2;
                    temp.fl_turnover3 = flow.fl_turnover3;
                    db.SaveChanges();
                    return Json("添加成功");
                }
                else
                {
                    db.flow.Add(flow);
                    int temp = db.SaveChanges();
                    string powasd = temp > 0 ? "添加成功" : "添加失败";
                    return Json(powasd);
                }
            }
            return View();
        }

        public ActionResult addsys(List<system> flows)
        {
            foreach (system flow in flows)
            {
                int index = db.system.Where(x => x.pro_id == flow.pro_id).Count();
                if (index > 0)
                {
                    system temp = db.system.Where(s => s.pro_id == flow.pro_id).FirstOrDefault();
                    temp.sys_fl = flow.sys_fl;
                    temp.sys_fw = flow.sys_fw;
                    temp.sys_tgbg = flow.sys_tgbg;
                    temp.sys_tgrz = flow.sys_tgrz;
                    temp.sys_jltx = flow.sys_jltx;
                    temp.sys_wbxk = flow.sys_wbxk;
                    temp.sys_jckq = flow.sys_jckq;
                    temp.sys_pjjg = flow.sys_pjjg;
                    temp.sys_sx = flow.sys_sx;
                    temp.sys_syzl = flow.sys_syzl;
                    db.SaveChanges();
                    return Json("添加成功");
                }
                else
                {
                    db.system.Add(flow);
                    int temp = db.SaveChanges();
                    string powasd = temp > 0 ? "添加成功" : "添加失败";
                    return Json(powasd);
                }
            }
            return View();
        }
        public ActionResult add(List<flow> flows)
        {
            foreach (flow flow in flows)
            {
                int index = db.flow.Where(x => x.pr_id == flow.pr_id).Count();
                if (index > 0)
                {
                    flow temp = db.flow.Where(s => s.pr_id == flow.pr_id).FirstOrDefault();
                    temp.fl_cfmj = flow.fl_cfmj;
                    temp.fl_cgsp = flow.fl_cgsp;
                    temp.fl_clsj = flow.fl_clsj;
                    temp.fl_gslb = flow.fl_gslb;
                    temp.fl_gykh = flow.fl_gykh;
                    temp.fl_sqyy = flow.fl_sqyy;
                    temp.fl_turnover1 = flow.fl_turnover1;
                    temp.fl_turnover2 = flow.fl_turnover2;
                    temp.fl_turnover3 = flow.fl_turnover3;
                    db.SaveChanges();
                    return Json("添加成功");
                }
                else
                {
                    db.flow.Add(flow);
                    int temp = db.SaveChanges();
                    string powasd = temp > 0 ? "添加成功" : "添加失败";
                    return Json(powasd);
                }
            }
            return View();
        }
        public JsonResult addcer(List<certificate> des)
        {
            string all = "";
            try
            {
                int index = 0;
                foreach (certificate a in des)
                {
                    using (LDbaseEntities db = new LDbaseEntities())
                    {
                        if (des == null)
                        {
                            des = new List<certificate>();
                        }
                        db.certificate.Add(a);
                        index += db.SaveChanges();
                    }
                }
                all = "新增:" + index + "条";
            }
            catch (Exception ex)
            {
                all = ex.Message;
            }

            return Json(all);
        }

        public JsonResult addfile(List<profile> des)
        {
            string all = "";
            try
            {
                int index = 0;
                foreach (profile a in des)
                {
                    using (LDbaseEntities db = new LDbaseEntities())
                    {
                        if (des == null)
                        {
                            des = new List<profile>();
                        }
                        db.profile.Add(a);
                        index += db.SaveChanges();
                    }
                }
                all = "新增:" + index + "条";
            }
            catch (Exception ex)
            {
                all = ex.Message;
            }

            return Json(all);
        }

        public ActionResult JJInksm(string SHun, string AP_bian = "", string App_Kehu = "", string App_JTime = "", int renid = 0, int states = 0, int RENY = 0)
        {
            List<Applications> app = db.Applications.Where(s => s.AP_bian.Contains("SQ") && s.App_bei == "提交" && s.AP_QTJY == null && (s.App_bu == "3" || s.App_bu == "4" || s.App_bu == "5") && s.App_zhand != "3").OrderByDescending(s => s.App_qishi).ToList();
            ViewBag.C_App = app;
            if (states == 1)
            {
                var shu = app.Where(s => s.AP_bian.Contains(AP_bian) && s.App_Kehu.Contains(App_Kehu) && s.APP_name.Contains(App_JTime)).ToList();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(shu, settings);
                return Content(jsongStr, "application/json");
            }
            else if (states == 2)
            {
                var list = db.BOMini.Where(x => x.BOM2_bian == AP_bian).ToList();
                var temp = from a in list
                           select new { a.BOM2_Lei };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (states == 3)
            {
                var lisst_bu = db.duty.Where(x => x.dl_id == renid).ToList();
                var list = db.BOMini.Where(x => x.BOM2_bian == AP_bian).ToList();
                var index = 0;
                foreach (duty duty in lisst_bu)
                {
                    foreach (BOMini bom in list)
                    {
                        if (bom.BOM2_ST == duty.du_name)
                        {
                            index++;
                        }
                    }
                }
                string num = "";
                if (index != 0)
                {
                    num = "添加";
                }
                else
                {
                    num = "不添加";
                }
                return Json(num);
            }
            else if (states == 5)
            {
                string jg = "";
                int indss = 0;
                var bom = db.BOMini.Where(x => x.BOM2_bian == AP_bian).ToList();//RENY:1 销售，0 采购
                if (RENY == 1)
                {
                    bom = db.BOMini.Where(x => x.BOM2_bian == AP_bian && x.BOM2_Lei == "自制").ToList();
                }
                else
                {
                    bom = db.BOMini.Where(x => x.BOM2_bian == AP_bian && x.BOM2_Lei == "外购").ToList();
                }
                foreach (BOMini b in bom)
                {
                    if (b.BOM2_GY != "完成")
                    {
                        indss++;
                    }
                }
                if (indss == 0)
                {
                    jg = "不添加";
                }
                else
                {
                    jg = "添加";
                }
                return Json(jg);
            }
            return View();
        }
        //修改数据
        [HttpPost]
        public JsonResult bomini(List<BOMini> bOMinis)
        {
            if (bOMinis == null)
            {
                bOMinis = new List<BOMini>();
            }
            int a = 0;
            foreach (var item in bOMinis)
            {
                var A = item.BOM2_id;
                var bom = db.BOMini.FirstOrDefault(s => s.BOM2_id == A);
                bom.BOM2_Jin = item.BOM2_Zhuang;
                db.Entry<BOMini>(bom).State = EntityState.Modified;
                a += db.SaveChanges();
            }
            return Json(a);
        }

        ///获取文件夹路径
        [HttpPost]
        public JsonResult SelectPath(int shu = 0)
        {
            try
            {
                var wenjainpath = GY.SelectwenPath();
                return Json(wenjainpath);
            }
            catch (Exception)
            {

                return Json(new { Success = false, Message = "系统错误！" });
            }

        }
        //选择文件
        [HttpPost]
        public ActionResult SelectFilePath(int shu = 0)
        {
            try
            {
                var wenjainpath = GY.SelectPath();
                return Json(wenjainpath);
            }
            catch (Exception)
            {
                return Json(new { Success = false, Message = "系统错误！" });
            }
        }
        /*[HttpPost]
        public ActionResult SelectFilePathADD(int shu = 0)
        {
            try
            {
                var wenjainpath = GY.SelectPath();
                return Json(wenjainpath);
            }
            catch (Exception)
            {
                return Json(new { Success = false, Message = "系统错误！" });
            }
        }*/

        public ActionResult Modify_Download_path(Dengli dl)
        {
            int rows = dl.DE_ID;
            var denamnr = db.Dengli.FirstOrDefault(s => s.DE_ID == rows);
            denamnr.DE_dizhi = dl.DE_dizhi;
            db.Entry(denamnr).State = EntityState.Modified;
            int sun = db.SaveChanges();
            string mess = sun > 0 ? "修改成功" : "修改失败";
            return Json(mess);
        }

        //修改密码
        [HttpPost]
        public ActionResult ChagnPwd(string oldpwd, string newpwd, string newpwd2)
        {
            string mess = "";
            string repasss = @"^(?=.*\d)(?=.*[a-z])[a-z0-9]{6,12}$";
            var inf = Regex.Matches(newpwd, repasss);
            var users = db.Dengli.Find(MyAuthentication.GetUserId());
            if (ModelState.IsValid)
            {
                if (oldpwd != users.DE_Pass)
                {
                    mess = "密码输入错误";
                }
                else if (inf.Count <= 0)
                {
                    mess = "新密码不符合要求";
                }
                else if (newpwd != newpwd2)
                {
                    mess = "两次密码输入不正确！";
                }
                else
                {
                    try
                    {
                        users.DE_Pass = newpwd;
                        db.Entry(users).State = EntityState.Modified;
                        int sun = db.SaveChanges();
                        mess = sun > 0 ? "修改成功" : "修改失败";
                    }
                    catch (Exception ex)
                    {
                        mess = "错误提示：" + ex.Message;
                    }

                }
            }
            return Json(mess);
        }
        //获取Excel文件并打开
        [HttpPost]
        public ActionResult ExcelFilePath(HttpPostedFileBase file)
        {
            var path = "";
            if (path == "")
            {
                try
                {
                    //解决方案 先保存到服务器后使用
                    if (file != null && file.ContentLength > 0)
                    {
                        // 指定保存文件的路径（服务器上的实际路径）  
                        path = Server.MapPath("~/Files/");
                        // 确保目录存在  
                        Directory.CreateDirectory(path);

                        // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                        string fileName = file.FileName;//只保存一个文件 有文件就删除

                        // 保存文件到服务器  
                        string filePath = Path.Combine(path, fileName);
                        file.SaveAs(filePath);//真实路径
                        System.Data.DataTable table = ExcelToDatatable(filePath, "Sheet1", true);


                        //自定义一个datatable
                        var table1 = new System.Data.DataTable();
                        table1.Columns.Add("BOM2_chen", typeof(string));
                        table1.Columns.Add("BOM2_duan", typeof(string));
                        table1.Columns.Add("BOM2_wuLiu", typeof(string));
                        table1.Columns.Add("BOM2_liao", typeof(string));
                        table1.Columns.Add("FM_long", typeof(string));
                        table1.Columns.Add("FM_kuan", typeof(string));
                        table1.Columns.Add("FM_gao", typeof(string));
                        table1.Columns.Add("BOM2_Nian", typeof(string));
                        table1.Columns.Add("BOM2_Yong", typeof(string));
                        table1.Columns.Add("BOM2_fenzi", typeof(string));
                        table1.Columns.Add("BOM2_Lei", typeof(string));
                        table1.Columns.Add("BOM2_mioa", typeof(string));
                        table1.Columns.Add("BOM2_Jin", typeof(string));//原材料
                        table1.Columns.Add("BOM2_Sone", typeof(string));
                        table1.Columns.Add("BOM2_ST", typeof(string));
                        table1.Columns.Add("BOM2_STeds", typeof(string));
                        //去除空值
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            DataRow dataRow = table.Rows[i];
                            if (dataRow["BOM2_chen"].ToString() != "")
                            {
                                var bomin = dataRow["BOM2_wuLiu"].ToString();//物料号
                                var liao = dataRow["BOM2_liao"].ToString();//料号
                                var KK = dataRow["BOM2_STeds"].ToString().Split(' ');
                                var Jiehuu = "";
                                for (int c = 0; c < KK.Length; c++)
                                {
                                    if (Jiehuu == "")
                                    {
                                        Jiehuu = KK[c];
                                    }
                                    else
                                    {
                                        Jiehuu = Jiehuu + "," + KK[c];
                                    }
                                }
                                var fojiwn = db.Formation.Where(s => s.FM_bai == liao || s.FM_name == bomin).ToList();
                                if (fojiwn.Count == 0)
                                {
                                    //
                                    var Jyong1 = "";
                                    var sone = dataRow["BOM2_ST"].ToString();
                                    var shu = db.buty2.FirstOrDefault(x => x.zl_name == sone);
                                    if (shu == null)
                                    {
                                        if (sone == "纸护角" || sone == "纸管" || sone == "蜂窝制品" || sone == "纸托盘" || sone == "纸塑")
                                        {
                                            Jyong1 = "纸制品";
                                        }
                                    }
                                    else
                                    {
                                        var Jyong = shu.zl2_id;
                                        var shu1 = db.buty2.FirstOrDefault(x => x.zl_name == sone);
                                        Jyong1 = shu1.zl_name;
                                    }
                                    var inde = db.Formation.Where(s => s.FM_bai.Contains("WL")).ToList();
                                    var ali = "WL" + inde[inde.Count() - 1].FM_ID.ToString();
                                    var shund = new Formation();
                                    shund.FM_bai = ali;
                                    decimal number = 0, number1 = 0, number2 = 0;
                                    shund.FM_name = bomin;
                                    decimal.TryParse(dataRow["FM_long"].ToString(), out number);
                                    decimal.TryParse(dataRow["FM_kuan"].ToString(), out number1);
                                    decimal.TryParse(dataRow["FM_gao"].ToString(), out number2);
                                    shund.FM_long = number;
                                    shund.FM_kuan = number1;
                                    shund.FM_gao = number2;
                                    shund.FM_ji = dataRow["BOM2_fenzi"].ToString();
                                    shund.FM_Zhuang = dataRow["BOM2_Lei"].ToString();
                                    shund.FM_gg = dataRow["FM_long"].ToString() + "*" + dataRow["FM_kuan"].ToString() + "*" + dataRow["FM_gao"].ToString();
                                    shund.FM_nyl = dataRow["BOM2_Nian"].ToString();
                                    shund.FM_ycl = dataRow["BOM2_Jin"].ToString();
                                    shund.FM_ms = dataRow["BOM2_mioa"].ToString();
                                    shund.FM_yj = Jyong1;
                                    shund.FM_ej = sone;
                                    shund.FM_Jieti = Jiehuu;
                                    db.Formation.Add(shund);
                                    db.SaveChanges();
                                    dataRow["BOM2_liao"] = ali;
                                }
                                else
                                {
                                    foreach (var m in fojiwn)
                                    {
                                        dataRow["BOM2_liao"] = m.FM_bai;
                                        dataRow["BOM2_STeds"] = Jiehuu;
                                    }
                                }
                                table1.ImportRow(dataRow);
                            }
                        }
                        JsonSerializerSettings settings = new JsonSerializerSettings();
                        string jsongStr = JsonConvert.SerializeObject(table1, settings);
                        return Content(jsongStr, "application/json");
                    }
                    else
                    {
                        // 返回失败消息  
                        return Json(new { success = false, message = "没有文件被上传或者文件大小为0." });
                    }
                }
                catch (Exception)
                {
                    return Json(new { Success = false, Message = "系统错误！" });
                }
            }



            return View();
        }
        public ActionResult APPoptiosjn(operational OPtas, int stannd = 0, string BOM2_id = "", string ZBLx = "", string zbll = "", string HSJIN = "")
        {
            if (stannd == 1)
            {
                var shunf = int.Parse(BOM2_id);
                var BOMjsd = db.BOMini.FirstOrDefault(s => s.BOM2_id == shunf);
                var jidnm = BOMjsd.BOM2_Gong;
                string message = "";
                var opert = db.operational.FirstOrDefault(s => s.OP_ID == jidnm);//价格库
                if (opert == null)
                {
                    db.operational.Add(OPtas);
                    db.SaveChanges();
                    BOMjsd.BOM2_Gong = OPtas.OP_ID;
                    db.Entry(BOMjsd).State = EntityState.Modified;
                    int shung = db.SaveChanges();
                    message = shung > 0 ? "添加成功" : "添加失败";
                }
                else
                {
                    opert.OP_jiehe = OPtas.OP_jiehe;
                    opert.OP_price = OPtas.OP_price;
                    opert.OP_YUN = OPtas.OP_YUN;
                    opert.OP_CAi = OPtas.OP_CAi;
                    opert.OP_JIA = OPtas.OP_JIA;
                    opert.OP_GUAN = OPtas.OP_GUAN;
                    opert.OP_LR = OPtas.OP_LR;
                    db.Entry(opert).State = EntityState.Modified;
                    int snji = db.SaveChanges();
                    message = snji > 0 ? "添加成功" : "添加失败";
                }
                return Json(message);
            }
            if (stannd == 2)
            {
                List<List<object>> result = NewMethod(ZBLx, zbll, HSJIN);
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(result, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }

        public static List<List<object>> NewMethod(string ZBLx, string zbll, string HSJIN)
        {
            DateTime now = DateTime.Now;
            string currentDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            K3CloudApi client = new K3CloudApi();
            //用于记录结果
            StringBuilder Info = new StringBuilder();
            //业务对象标识
            string formId = "PSH_PaperQmPrice";
            //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
            string fieldKeys = "FName,F_PSH_QmPrice,F_PSH_MatTypeId.FDataValue";
            string FS = "";
            if (HSJIN == "彩盒纸板")
            {
                FS = "F_PSH_MatTypeId.FDataValue like'%" + ZBLx + "%'and F_PSH_LengXingId.FDataValue ='" + zbll + "'and F_PSH_DateTo >'" + currentDateTime + "'and F_PSH_Disabled='0' and FForbidStatus='A' and FDocumentStatus='C' and F_SMGS_ZBLX.FDataValue like'%" + HSJIN + "'";
            }
            else
            {
                FS = "F_PSH_MatTypeId.FDataValue like'%" + ZBLx + "%'and F_PSH_LengXingId.FDataValue ='" + zbll + "'and F_PSH_DateTo >'" + currentDateTime + "'and F_PSH_Disabled='0'and FForbidStatus='A' and FDocumentStatus='C' and  F_SMGS_ZBLX.FDataValue is null";
            }
            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式  F_SMGS_ZBLX.FDataValue:纸版类型
            var param = new QueryParam()
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = FS,
                TopRowCount = 0,
                StartRow = 0,
                Limit = 50,
            };
            //调用接口
            var result = client.ExecuteBillQuery(param.ToJson());
            return result;
        }

        //导出Excel文件
        public ActionResult Ecssxsdd(int shu = 0, string Employee_path = null, string excelName = "")
        {
            if (shu == 1)
            {
                try
                {
                    var lujing = Server.MapPath("~\\Files\\BOM批量添加模板.xlsx");
                    var text = lujing;
                    var parts = text.Split('\\');
                    var lastElement = parts[parts.Length - 1];

                    FileStream fs = new FileStream(lujing, FileMode.Open);
                    byte[] bytes = new byte[(int)fs.Length];   //以字符流的形式下载文件
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    Response.Charset = "UTF-8";
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                    Response.ContentType = "application/octet-stream";  //通知浏览器下载文件而不是打开

                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(lastElement));
                    Response.BinaryWrite(bytes);
                    Response.Flush();
                    Response.End();
                    return new EmptyResult();
                }
                catch (Exception)
                {
                    throw;
                }
            }
            if (shu == 67)
            {
                try
                {
                    var lujing = Server.MapPath("~\\Files\\ERP物料批量添加.xlsx");
                    var text = lujing;
                    var parts = text.Split('\\');
                    var lastElement = parts[parts.Length - 1];
                    FileStream fs = new FileStream(lujing, FileMode.Open);
                    byte[] bytes = new byte[(int)fs.Length];   //以字符流的形式下载文件
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    Response.Charset = "UTF-8";
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                    Response.ContentType = "application/octet-stream";  //通知浏览器下载文件而不是打开

                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(lastElement));
                    Response.BinaryWrite(bytes);
                    Response.Flush();
                    Response.End();
                    return new EmptyResult();
                }
                catch (Exception)
                {
                    throw;
                }
            }
            return View();
        }
        public ActionResult AddProcessRecord(ProcessRecord pr)
        {
            var id = pr.wl_liao;
            int pro = db.ProcessRecord.Where(s => s.wl_liao == id).Count();
            string index = "";
            if (pro > 0)
            {
                var KK = pr.wl_liao;
                var hujjn = db.ProcessRecord.Where(s => s.wl_liao == KK).FirstOrDefault();
                hujjn.wl_leng = pr.wl_leng;
                hujjn.wl_xing = pr.wl_xing;
                hujjn.wl_gui = pr.wl_gui;
                hujjn.wl_c = pr.wl_c;
                hujjn.wl_k = pr.wl_k;
                hujjn.wl_g = pr.wl_g;
                hujjn.wl_h = pr.wl_h;
                hujjn.wl_m = pr.wl_m;
                hujjn.wl_mj = pr.wl_mj;
                hujjn.wl_ll = pr.wl_ll;
                hujjn.wl_sj = pr.wl_sj;
                db.Entry(hujjn).State = EntityState.Modified;
                int JL = db.SaveChanges();
                index = hujjn.prr_id.ToString();
            }
            else
            {
                db.ProcessRecord.Add(pr);
                db.SaveChanges();
                index = db.ProcessRecord.OrderByDescending(b => b.prr_id).First().prr_id.ToString();
            }
            return Content(index);
        }

        public JsonResult addCraftMaterials(List<CraftMaterials> des)
        {
            int index = 0;

            foreach (CraftMaterials a in des)
            {
                var id = a.prr_id;
                var cl = db.CraftMaterials.Where(s => s.prr_id == id).ToList();
                var uni = cl.Count();
                if (uni > 0)
                {
                    var shij = 0;
                    foreach (var item in cl)
                    {
                        db.CraftMaterials.Remove(item);
                        shij += db.SaveChanges();
                    }

                }
            }
            foreach (var item in des)
            {
                if (des == null)
                {
                    des = new List<CraftMaterials>();
                }
                db.CraftMaterials.Add(item);
                index += db.SaveChanges();
            }
            string all = "新增:" + index + "条";
            return Json(all);
        }

        public JsonResult addProcessFlow(List<ProcessFlow> des)
        {
            int index = 0;
            int indexwd = 0;
            if (des == null)
            {
                des = new List<ProcessFlow>();
            }
            foreach (ProcessFlow a in des)
            {
                var id = a.prr_id;
                var cl = db.ProcessFlow.Where(s => s.prr_id == id).ToList();
                var uni = cl.Count();
                if (uni > 0)
                {
                    foreach (var item in cl)
                    {
                        db.ProcessFlow.Remove(item);
                        indexwd += db.SaveChanges();
                    }
                }
            }
            foreach (var item in des)
            {
                db.ProcessFlow.Add(item);
                index += db.SaveChanges();
            }
            string all = "新增:" + index + "条";
            return Json(all);
        }
        public ActionResult ERPGongy(string names, int state = 0)
        {
            //names = "SQ202311219556113 ";
            names = names == null ? "-1" : names;
            List<Applications> xian = db.Applications.Where(a => a.AP_bian == names).ToList();/*查询客户*/
            Session["appp_id"] = names;
            /*遍历工艺库是工艺根据种类分类*/
            var Yinshua = db.libray.ToList();  //印刷--1，结合--21，模具--22，表面处理--2，吸塑--6
            ViewBag.Yinshua = Yinshua;  //传递到前台--印刷
            var ListZBxx = FP.find_lib();
            ViewBag.ListZBxx = ListZBxx;
            ViewBag.ListPP = FP.find_manufacturer();
            ViewBag.ListZL = FP.find_ZL_();
            ViewBag.ListPO = FP.find_projectprs();
            ViewBag.parice = FP.find_parices();
            ViewBag.ro = FP.find_Rou();
            ViewBag.par = FP.find_parices();
            ViewBag.par_hc = FP.find_Rou_HC();
            ViewBag.Yun = FP.YUNF();
            ViewBag.JX = FP.jicsin();
            ViewBag.ro_xs = FP.find_Rou_XS();
            if (state == 1)
            {
                var listBOMw = db.BOMini.Where(x => x.BOM2_bian == names && x.operational.OP_ID == x.BOM2_Gong).ToList();
                List<BOMini> list2 = new List<BOMini>();
                foreach (BOMini b in listBOMw)
                {
                    var jeiji = b.BOM2_BQing;
                    int twwe = listBOMw.Where(x => x.BOM2_BQing != jeiji && x.BOM2_BQing.Contains(jeiji)).Count();
                    if (twwe == 0)
                    {
                        list2.Add(b);
                    }
                }
                var list = from a in list2 select new { a.BOM2_id, a.BOM2_chen, a.BOM2_duan, a.BOM2_liao, a.BOM2_wuLiu, a.BOM2_Nian, a.BOM2_Yong, a.BOM2_Sone, a.BOM2_BQing, a.BOM2_Guige, a.BOM2_ST, a.BOM2_Lei, BOM2_mioa = a.operational == null ? "0" : a.operational.OP_price.ToString() };
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    Formatting = Formatting.Indented
                };
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }

        public ActionResult Addpaid(string name)
        {
            string index = db.parice.Where(x => x.PA_ZhongL == name).First().PA_ID.ToString();
            return Content(index, "text / plain");
        }
        public ActionResult Addliid(string name)
        {
            string index = db.libray.Where(x => x.LB_fne == name).First().LB_ID.ToString();
            return Content(index, "text / plain");
        }
        #region 读取Excel数据
        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名，true是</param>
        /// <returns>返回的DataTable</returns>从第二行开始遍历
        public static System.Data.DataTable ExcelToDatatable(string fileName, string sheetName, bool isFirstRowColumn)
        {
            System.Data.DataTable data = new System.Data.DataTable();
            int startRow = 0;
            int cellCount = 0;//列数
            int rowCount = 0;//行数
            try
            {
                using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    // 创建HSSFWorkbook或XSSFWorkbook对象，取决于你的Excel文件格式  
                    IWorkbook workbook;
                    if (System.IO.Path.GetExtension(fileName).Equals(".xls"))
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new XSSFWorkbook(fs);
                    }

                    // 获取第一个工作表  
                    ISheet sheet = workbook.GetSheetAt(0);
                    if (sheet != null)
                    {
                        IRow firstRow = sheet.GetRow(0);
                        cellCount = firstRow.LastCellNum; //第一行最后一个cell的编号 即总的列数
                        if (isFirstRowColumn)//如果第一行是标题行
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)//第一行列数循环
                            {
                                DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue);//获取标题
                                data.Columns.Add(column);//添加列
                            }
                            startRow = sheet.FirstRowNum + 2;//1（即第二行，第一行0从开始）
                        }
                        else
                        {
                            startRow = sheet.FirstRowNum;//0
                        }
                        //最后一行的标号
                        rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)//循环遍历所有行
                        {
                            IRow row = sheet.GetRow(i);//第几行
                            if (row != null)
                            {
                                //将excel表每一行的数据添加到datatable的行中
                                DataRow dataRow = data.NewRow();
                                for (int j = row.FirstCellNum; j < cellCount; ++j)
                                {
                                    if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                    {
                                        dataRow[j] = row.GetCell(j).ToString();
                                    }
                                }
                                data.Rows.Add(dataRow);
                            }
                            else
                            {
                                continue; //没有数据的行默认是null;
                            }

                        }
                    }
                    return data;
                }
            }
            catch (Exception)
            {
                return data;
            }
        }
        //从第一行开始遍历
        public static System.Data.DataTable ExcelToDatatables(string fileName, string sheetName, bool isFirstRowColumn)
        {
            System.Data.DataTable data = new System.Data.DataTable();
            int startRow = 0;
            int cellCount = 0;//列数
            int rowCount = 0;//行数
            try
            {
                using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    // 创建HSSFWorkbook或XSSFWorkbook对象，取决于你的Excel文件格式  
                    IWorkbook workbook;
                    if (System.IO.Path.GetExtension(fileName).Equals(".xls"))
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new XSSFWorkbook(fs);
                    }

                    // 获取第一个工作表  
                    ISheet sheet = workbook.GetSheetAt(0);
                    if (sheet != null)
                    {
                        IRow firstRow = sheet.GetRow(0);
                        cellCount = firstRow.LastCellNum; //第一行最后一个cell的编号 即总的列数
                        if (isFirstRowColumn)//如果第一行是标题行
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)//第一行列数循环
                            {
                                DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue);//获取标题
                                if (column != null)
                                {
                                    data.Columns.Add(column);//添加列
                                }
                            }
                            startRow = sheet.FirstRowNum + 1;//1（即第二行，第一行0从开始）
                        }
                        else
                        {
                            startRow = sheet.FirstRowNum;//0
                        }
                        //最后一行的标号
                        rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)//循环遍历所有行
                        {
                            IRow row = sheet.GetRow(i);//第几行
                            if (row != null)
                            {
                                //将excel表每一行的数据添加到datatable的行中
                                DataRow dataRow = data.NewRow();
                                for (int j = row.FirstCellNum; j < cellCount; ++j)
                                {
                                    if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                    {
                                        dataRow[j] = row.GetCell(j).ToString();
                                    }
                                }
                                data.Rows.Add(dataRow);
                            }
                            else
                            {
                                continue; //没有数据的行默认是null;
                            }

                        }
                    }
                    return data;
                }
            }
            catch (Exception)
            {

                return data;
            }
        }
        #endregion
        #region 批量添加供应商
        public ActionResult Gonpl(HttpPostedFileBase file)
        {

            var path = "";
            if (path == "")
            {
                try
                {
                    //解决方案 先保存到服务器后使用
                    if (file != null && file.ContentLength > 0)
                    {
                        // 指定保存文件的路径（服务器上的实际路径）  
                        path = Server.MapPath("~/Files/");
                        // 确保目录存在  
                        Directory.CreateDirectory(path);

                        // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                        string fileName = file.FileName;//只保存一个文件 有文件就删除

                        // 保存文件到服务器  
                        string filePath = Path.Combine(path, fileName);
                        file.SaveAs(filePath);//真实路径
                        System.Data.DataTable table = ExcelToDatatables(filePath, "Sheet1", true);
                        //去除空值  直接保存
                        int sjinag = 0;
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            DataRow dataRow = table.Rows[i];
                            var bian = dataRow[0].ToString();
                            var cuzn = db.Providers.FirstOrDefault(s => s.PR_bian == bian);
                            if (cuzn == null)
                            {
                                var clis = new Providers();
                                clis.PR_bian = bian.ToString();
                                clis.PR_name = dataRow[1].ToString();
                                clis.PR_Lei1 = dataRow[2].ToString();
                                clis.PR_Lei2 = dataRow[3].ToString();
                                clis.PR_bei = "准入";
                                db.Providers.Add(clis);
                            }
                            else
                            {
                                cuzn.PR_bian = bian.ToString();
                                cuzn.PR_name = dataRow[1].ToString();
                                cuzn.PR_Lei1 = dataRow[2].ToString();
                                cuzn.PR_Lei2 = dataRow[3].ToString();
                                cuzn.PR_bei = "准入";
                                db.Entry(cuzn).State = EntityState.Modified;
                            }
                            sjinag += db.SaveChanges();
                        }
                        string message = sjinag == table.Rows.Count ? "添加成功" : "添加失败";
                        return Content(message);
                    }
                    else
                    {
                        // 返回失败消息  
                        return Json(new { success = false, message = "没有文件被上传或者文件大小为0." });
                    }
                }
                catch (DbEntityValidationException)
                {

                    return Json(new { Success = false, Message = "系统错误！" });
                }
            }

            return View();
        }
        #endregion
        #region 工艺记录恢复
        [HttpPost]
        public ActionResult GongYiHuiFU(int state = 0, string Bomid = "")
        {
            //判断该物料是佛存在
            if (state == 1)
            {
                var desJL = db.ProcessRecord.Where(s => s.wl_liao == Bomid).ToList();
                if (desJL == null)
                {
                    desJL = new List<ProcessRecord>();
                }
                //返回全部
                var list = from a in desJL select new { a.wl_c, a.wl_fen, a.wl_name, a.wl_k, a.wl_g, a.wl_gui, a.wl_h, a.wl_leng, a.wl_liao, a.wl_m, a.wl_mj, a.wl_xing, a.wu_fenLei, a.wl_ll };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            if (state == 2)
            {
                var desJL = db.ProcessRecord.Where(s => s.wl_liao == Bomid).ToList();
                //去原材料的
                var liasohd = new List<parice>();
                foreach (ProcessRecord a in desJL)
                {
                    var id = a.prr_id;
                    var cl = db.CraftMaterials.Where(s => s.prr_id == id).ToList();
                    if (cl.Count() > 0)
                    {
                        foreach (var item in cl)
                        {
                            var died = item.cl_id;
                            var shu = db.parice.Where(s => s.PA_ID == died).FirstOrDefault();
                            liasohd.Add(shu);
                        }
                    }
                }
                var list = from a in liasohd where a != null select new { a.PA_Pinpai, a.PA_ZhongL, a.PA_KZ, a.PA_T, a.PA_Time, a.PA_LengBie, a.PA_Shuxing, a.PA_ID };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            if (state == 3)
            {
                var desJL = db.ProcessRecord.Where(s => s.wl_liao == Bomid).ToList();
                //找工艺
                var liasohd = new List<libray>();
                var cl = new List<ProcessFlow>();
                foreach (ProcessRecord a in desJL)
                {
                    var id = a.prr_id;
                    cl = db.ProcessFlow.Where(s => s.prr_id == id).ToList();
                    if (cl.Count() > 0)
                    {
                        foreach (var item in cl)
                        {
                            var died = item.gy_id;
                            var shu = db.libray.Where(s => s.LB_ID == died).FirstOrDefault();
                            liasohd.Add(shu);
                        }
                    }
                }

                var list = from c in cl
                           where c != null  // 添加额外的null检查  
                           select new
                           {
                               LB_fne = c.gy_id == null ? "" : c.libray.LB_fne, // 由于已经做了null检查，这里不需要再检查  
                               jiage = c.pfw_jia ?? "", // 使用null合并运算符来提供默认值  
                               JUn = c.pfw_gg ?? "", // 同样使用null合并运算符  
                               BeiZ = c.CL_beizhu ?? "", // 同样使用null合并运算符  
                               JiaoG = c.gy_id == null ? "" : c.libray.LB_jia + "+" + c.libray.LB_ID,
                               ZC = c.pfw_zc,
                               ZF = c.pfw_Zhengfan
                           };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            if (state == 4)
            {
                //查询物料的工艺级别
                var Bid = int.Parse(Bomid);
                var BOM = db.BOMini.Find(Bid).BOM2_Gong;
                var OP = BOM == null ? "" : db.operational.Find(BOM).OP_jiehe;
                var JT = OP.Split(';');
                var SOP = new System.Data.DataTable();
                SOP.Columns.Add("JieH");
                SOP.Columns.Add("Pric");
                for (int i = 0; i < JT.Length; i++)
                {
                    if (JT[i] != "")
                    {
                        var H = JT[i].Split(':')[0];
                        var P = JT[i].Split(':')[1];
                        SOP.Rows.Add(H, P);
                    }
                }
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(SOP, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
        #endregion
        #region 供应商信息同步
        [HttpPost]
        public ActionResult GYSerptonn(int state = 0)
        {
            if (state == 1)
            {
                K3CloudApi client = new K3CloudApi();
                //用于记录结果
                StringBuilder Info = new StringBuilder();
                //业务对象标识
                string formId = "BD_Supplier";
                //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
                string fieldKeys = "FNumber,FName,FAddress,FPayCurrencyId.FName";
                string FS = "FForbidStatus='A' and FDocumentStatus ='C' and FUseOrgId.FNumber='10.01'";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式  F_SMGS_ZBLX.FDataValue:纸版类型
                var param = new QueryParam()
                {
                    FormId = formId,
                    FieldKeys = fieldKeys,
                    FilterString = FS,
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 2000,
                };
                //调用接口
                var result = client.ExecuteBillQuery(param.ToJson());

                if (result.Count > 1)
                {
                    //
                    System.Data.DataTable data = ERPZdata(result);
                    //排除重复
                    var shudd = db.Providers.ToList();
                    foreach (var item in shudd)
                    {
                        var bina = item.PR_bian;
                        if (bina.Length <= 2)
                        {
                            var TIhuan = int.Parse(bina);
                            bina = TIhuan < 10 ? "00" + TIhuan : TIhuan < 100 ? "0" + TIhuan : TIhuan.ToString();
                        }
                        var HUsn = data.Select("FNumber='" + bina + "'");
                        if (HUsn != null)
                        {
                            foreach (var FHU in HUsn)
                            {
                                FHU.Delete();
                            }
                        }
                    }
                    data.AcceptChanges();
                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                        Formatting = Formatting.Indented
                    };
                    string jsongStrwe = JsonConvert.SerializeObject(data, settings);
                    return Content(jsongStrwe, "application/json");
                }
                else
                {
                    return Content("1");
                }

            }
            return View();
        }
        public JsonResult APrERp(List<Providers> des)
        {
            string meeas = "2";
            if (des.Count > 0)
            {
                var sjinag = 0;
                foreach (Providers p in des)
                {
                    var bian = p.PR_bian;
                    var cuzn = db.Providers.FirstOrDefault(s => s.PR_bian == bian);
                    if (cuzn == null)
                    {
                        var clis = new Providers();
                        clis.PR_bian = bian.ToString();
                        clis.PR_name = p.PR_name;
                        clis.PR_di = p.PR_di;
                        clis.PR_Lei1 = p.PR_Lei1;
                        clis.PR_Lei2 = p.PR_Lei2;
                        clis.PR_bei = "准入";
                        db.Providers.Add(clis);
                    }
                    else
                    {
                        cuzn.PR_bian = bian.ToString();
                        cuzn.PR_name = p.PR_name;
                        cuzn.PR_di = p.PR_di;
                        cuzn.PR_Lei1 = p.PR_Lei1;
                        cuzn.PR_Lei2 = p.PR_Lei2;
                        cuzn.PR_bei = "准入";
                        db.Entry(cuzn).State = EntityState.Modified;
                    }
                    sjinag += db.SaveChanges();
                }
                meeas = "新增" + sjinag + "条";
            }
            return Json(meeas);
        }
        private static System.Data.DataTable ERPZdata(List<List<object>> result)
        {
            var data = new System.Data.DataTable();
            data.Columns.Add("FNumber", typeof(string));
            data.Columns.Add("FName", typeof(string));
            data.Columns.Add("FAddress", typeof(string));
            data.Columns.Add("FBankCurrencyId", typeof(string));
            for (int i = 0; i < result.Count; i++)
            {
                data.Rows.Add(result[i][0], result[i][1], result[i][2], result[i][3]);
            }

            return data;
        }
        #endregion
        #region 批量上传原材料
        public ActionResult Yuanpl(HttpPostedFileBase file)
        {

            var path = "";
            if (path == "")
            {
                int sjinag = 0;//更新成功
                var Gxingz = 0;//未更新成功
                try
                {
                    //解决方案 先保存到服务器后使用
                    if (file != null && file.ContentLength > 0)
                    {
                        string Y = DateTime.Now.Year.ToString();
                        string M = DateTime.Now.Month.ToString();
                        // 指定保存文件的路径（服务器上的实际路径）  
                        path = Server.MapPath("~/Files/");
                        // 确保目录存在  
                        Directory.CreateDirectory(path);

                        // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                        string fileName = file.FileName;//只保存一个文件 有文件就删除

                        // 保存文件到服务器  
                        string filePath = Path.Combine(path, fileName);
                        file.SaveAs(filePath);//真实路径
                        System.Data.DataTable table = ExcelToDatatables(filePath, "Sheet1", true);
                        //去除空值  直接保存
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            DataRow dataRow = table.Rows[i];//行字段: 品牌 原料名 种类 克重 吨价 Id
                            var bian = dataRow[6].ToString(); //Id是否为空
                            if (bian != null && bian != "")
                            {
                                var pa = db.parice.Find(int.Parse(bian));
                                var Paric = dataRow[4].ToString(); //价格是否为空
                                if (decimal.Parse(Paric) == pa.PA_T)
                                {
                                    pa.PA_T = pa.PA_T;
                                }
                                else
                                {
                                    pa.PA_T = (decimal)double.Parse(Paric);
                                }
                                pa.PA_Time = DateTime.Now.ToString("yyyy-M-dd");
                                db.Entry(pa).State = EntityState.Modified;
                                int A = db.SaveChanges();
                                if (A > 0)
                                {
                                    sjinag++;
                                    var Paid = pa.PA_ID;
                                    using (LDbaseEntities LD = new LDbaseEntities())
                                    {
                                        var format = LD.parice.Where(x => x.PA_ID == Paid).First();
                                        var currentTime = DateTime.Now.ToString("yyyy/M/d H:m:s");
                                        LanJiLu lan = new LanJiLu()
                                        {
                                            JL_Name = format.PA_ZhongL,
                                            JL_Time = currentTime,
                                            JL_Fen = "原材料",
                                            JL_Price = (format.PA_T).ToString(),
                                            JL_Y = Y,
                                            JL_M = M,
                                            JL_Fen2 = format.mateial == null ? null : format.mateial.MA_fne
                                        };
                                        LD.LanJiLu.Add(lan);
                                        LD.SaveChanges();
                                    }
                                }
                                else
                                {
                                    Gxingz++;
                                }
                            }
                            else
                            {
                                var hu = dataRow[5].ToString();
                                var shu = "";
                                if (hu != "")
                                {
                                    var mat = db.mateial.Where(s => s.MA_fne == hu).FirstOrDefault();
                                    shu = mat == null ? "" : mat.MA_ID.ToString();
                                }
                                var p = new parice()
                                {
                                    PA_Pinpai = dataRow[2].ToString(),
                                    PA_ZhongL = dataRow[0].ToString(),
                                    PA_KZ = dataRow[3].ToString(),
                                    PA_T = (decimal?)double.Parse(dataRow[4].ToString()),
                                    PA_Time = DateTime.Now.ToString("yyyy-M-dd"),
                                    PA_LengBie = dataRow[1].ToString(),
                                    PA_Shuxing = int.Parse(shu)
                                };
                                db.parice.Add(p);
                                int A = db.SaveChanges();
                                if (A > 0)
                                {
                                    sjinag++;
                                }
                                else
                                {
                                    Gxingz++;
                                }
                            }
                        }
                        string message = "更新" + sjinag + "行,未更新" + Gxingz + "行";
                        return Content(message);
                    }
                    else
                    {
                        // 返回失败消息  
                        return Json(new { success = false, message = "没有文件被上传或者文件大小为0." });
                    }
                }
                catch (DbEntityValidationException ex)
                {
                    return Json(new { Success = false, Message = ex.Message });
                }
            }

            return View();
        }
        #endregion
        #region 原材料文件下载
        public ActionResult DownloadExcel2(int state = 0, string excelName = null, int WT_CD = 0, string Employee_path = null)
        {
            if (state == 1)
            {
                //Employee_path = Employee_path.Replace(" ", string.Empty);
                //Employee_path = Employee_path.Substring(0, Employee_path.Length - 1);
                //Employee_path = Employee_path.Substring(1);
                // 创建Excel文件
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                using (ExcelPackage excel = new ExcelPackage())
                {
                    // 添加工作表
                    var worksheet = excel.Workbook.Worksheets.Add("Sheet1");
                    // 写入数据
                    worksheet.Cells[1, 1].Value = "品牌";
                    worksheet.Cells[1, 2].Value = "原材料名";
                    worksheet.Cells[1, 3].Value = "类别";
                    worksheet.Cells[1, 4].Value = "原纸克重（克）";
                    worksheet.Cells[1, 5].Value = "含税价格（元/吨|元/M3)";
                    worksheet.Cells[1, 6].Value = "分组";
                    worksheet.Cells[1, 7].Value = "id";
                    int i = 2;
                    foreach (var item in db.mateial.ToList())
                    {
                        var hu = item.MA_ID;
                        var PricesWD = db.parice.Where(s => s.PA_Shuxing == hu).ToList();
                        foreach (parice des in PricesWD)
                        {
                            int index = 1;
                            worksheet.Cells[i, index].Value = des.PA_Pinpai;
                            index++;
                            worksheet.Cells[i, index].Value = des.PA_ZhongL;
                            index++;
                            worksheet.Cells[i, index].Value = des.PA_LengBie;
                            index++;
                            worksheet.Cells[i, index].Value = des.PA_KZ;
                            index++;
                            worksheet.Cells[i, index].Value = des.PA_T;
                            index++;
                            worksheet.Cells[i, index].Value = item.MA_fne;
                            index++;
                            worksheet.Cells[i, index].Value = des.PA_ID;
                            i++;
                        }
                    }
                    var PricesWD1 = db.parice.Where(s => s.PA_Shuxing == null).ToList();
                    foreach (parice des in PricesWD1)
                    {
                        int index = 1;
                        worksheet.Cells[i, index].Value = des.PA_Pinpai;
                        index++;
                        worksheet.Cells[i, index].Value = des.PA_ZhongL;
                        index++;
                        worksheet.Cells[i, index].Value = des.PA_LengBie;
                        index++;
                        worksheet.Cells[i, index].Value = des.PA_KZ;
                        index++;
                        worksheet.Cells[i, index].Value = des.PA_T;
                        index++;
                        worksheet.Cells[i, index].Value = "";
                        index++;
                        worksheet.Cells[i, index].Value = des.PA_ID;
                        i++;
                    }
                    worksheet.Cells["A:Z"].AutoFitColumns();
                    string path = "";
                    path = Server.MapPath("~/Files/");
                    string Name = "原材料信息修改.xlsx";
                    // 确保目录存在  
                    Directory.CreateDirectory(path);

                    // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                    string fileName = Path.GetFileNameWithoutExtension(Name) + "_" + Guid.NewGuid() + Path.GetExtension(Name);

                    // 保存文件到服务器  
                    string filePath = Path.Combine(path, fileName);
                    excel.SaveAs(filePath);
                    return Json(filePath);
                }
            }
            return View();
        }
        #endregion

    }
}